package com.sl.au.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Option;
import com.sl.au.service.OptionService;

@RestController
@RequestMapping(value = "/ui/option")
public class OptionController extends BaseController {

	
	@Autowired
	OptionService optionService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("optionSelect/optionindex");
		return modelAndView;
	}

	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		Long count = null;
		List<Option> options = null;
		if(StringUtils.hasText(key))
		{
		options = optionService.getOption(start, length, key, null, null);
		count = optionService.getRepository().getOptionCount(key);
		}
		else
		{
			options = optionService.getPage(start, length, null, null, null);
			count = optionService.getRepository().count();
		}
		map.put("data", options);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	///保存
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public Map<String, Object> saveOption(HttpServletRequest request, @RequestBody Option option) {
		Map<String, Object> map = new HashMap<String, Object>();
		optionService.getRepository().save(option);
		map.put("code", 0);
		return map;
	}
	@RequestMapping(value="/group/{groupName}",method = RequestMethod.GET)
	public List<Option> getByGroup(@PathVariable String groupName) {
		List<Option> list= optionService.getRepository().findByGroup(groupName);		
		return list;
	}
}
